const { defineConfig } = require("@vue/cli-service");
const TerserPlugin = require("terser-webpack-plugin");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

//https://wenku.baidu.com/view/bfb2021840323968011ca300a6c30c225901f03f.html
//https://github.com/Yatoo2018/webpack-chain/tree/zh-cmn-Hans
//https://webpack.js.org/configuration/
module.exports = defineConfig({
  outputDir: "wwwroot",
  productionSourceMap: false,
  transpileDependencies: true,
  filenameHashing: true,
  parallel: require("os").cpus().length > 1,
  devServer: {
    host: "localhost",
    port: 8010,
    open: true,
    hot: true,
    compress: true,
    https: false,
    proxy: {
      "/api": {
        target: "http://localhost:7675/api", // 目标代理服务器地址
        changeOrigin: true, // 允许跨域
        pathRewrite: {
          "^/api": "",
        },
      },
    },
  },
  chainWebpack: (config) => {
    if (process.env.NODE_ENV === "production") {
      config.optimization.minimize(true);
      config.plugin("webpack-bundle-analyzer").use(BundleAnalyzerPlugin);
      config.plugin("terser-webpack-plugin").use(TerserPlugin, [
        {
          terserOptions: {
            warnings: false,
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ["console.log"],
            },
          },
        },
      ]);
      config
        .plugin("compression-webpack-plugin")
        .use(CompressionWebpackPlugin, [
          {
            algorithm: "gzip",
            threshold: 0, //对只有⼤⼩⼤于该值的资源会被进⾏压缩
            test: /\.(js|ts|css|html|svg)$/i,
            minRatio: 0.8,
            deleteOriginalAssets: false,
          },
        ]);
      config.optimization.splitChunks(
        {
          cacheGroups: {
            common: {
              minChunks: 2,
              name: "common",
              priority: 5,
              reuseExistingChunk: true, // 重用已存在代码块
              test: /src/,
            },
            vendor: {
              chunks: "initial", // 代码分割类型
              name: "vendor", // 代码块名称
              priority: 10, // 优先级
              test: /node_modules/, // 校验文件正则表达式
            },
          }, // 缓存组
          chunks: "all", // 代码分割类型：all全部模块，async异步模块，initial入口模块
        } // 代码块分割
      );
    }
  },
});
